package com.ibm.moa.outmail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.moa.outmail.module.MailInfo;
import com.ibm.moa.outmail.net.HttpManage;
import com.ibm.moa.outmail.net.HttpRequestListener;
import com.ibm.moa.outmail.utils.DBHandler;
import com.ibm.moa.outmail.utils.ParserRequest;
import com.ibm.moa.outmail.utils.PropertiesUtils;
import com.ibm.moa.outmail.utils.UIEventListener;
import com.ibm.moa.outmail.utils.Utils;
import com.ibm.moa.outmail.view.MyWebView;

public class PublicMailActivity extends BaseActivity implements OnClickListener, HttpRequestListener {
	TextView titleText;
	ImageView ivBack, ivSend;
	EditText recAddrET, mailCcET, mailBccET, subjectET, contentET;
	MailInfo mailInfo;
	Dialog dialog;
	boolean getData = false;
	boolean isSend = false;
	MyWebView preContent;
	String preContentStr = "";

	ImageView recAddrADD, mailccADD, mailBccADD;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (msg.what) {
			case UIEventListener.EVENT_GET_DATA_SUCCESS:
				@SuppressWarnings("unchecked")
				HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
				if (map != null) {
					if ("1".equals(map.get("req_code"))) {
						Toast.makeText(PublicMailActivity.this, (String) map.get("req_mess") == null ? "发送成功" : (map.get("req_mess") + ""),
								Toast.LENGTH_SHORT).show();
						if (mailInfo == null) {
							mailInfo = new MailInfo();
						}
						mailInfo.recAddr = recAddrET.getText().toString().trim();
						mailInfo.from = MailApplication.userCode + PropertiesUtils.singlton().getProperty("MAILPATH");
						mailInfo.mailCc = mailCcET.getText().toString().trim();
						mailInfo.mailBcc = mailBccET.getText().toString().trim();
						mailInfo.subject = subjectET.getText().toString().trim();
						mailInfo.plainContent = contentET.getText().toString().trim();
						DBHandler db = new DBHandler(PublicMailActivity.this);
						db.addSendMail(mailInfo);
						Intent intent = new Intent(PublicMailActivity.this, HomeActivity.class);
						intent.putExtra("userName", MailApplication.userCode);
						intent.putExtra("password", MailApplication.passWord);
						startActivity(intent);
						finish();
					} else {
						Toast.makeText(PublicMailActivity.this, (String) map.get("req_mess") == null ? "返回信息错误" : (map.get("req_mess") + ""),
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case UIEventListener.EVENT_GET_DATA_FAILURE:
				Toast.makeText(PublicMailActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mail);
		if (getIntent().getStringExtra("userName") != null) {
			MailApplication.userCode = getIntent().getStringExtra("userName") == null ? "" : getIntent().getStringExtra("userName");
			MailApplication.passWord = getIntent().getStringExtra("password") == null ? "" : getIntent().getStringExtra("password");
		}
		ivBack = (ImageView) findViewById(R.id.home_back_iv);
		ivBack.setOnClickListener(this);
		ivSend = (ImageView) findViewById(R.id.mail_send_bt);
		ivSend.setOnClickListener(this);
		titleText = (TextView) findViewById(R.id.mail_title_tv);
		titleText.setText("新邮件");

		recAddrADD = (ImageView) findViewById(R.id.mail_recAddr_add_iv);
		mailccADD = (ImageView) findViewById(R.id.mail_mailcc_add_iv);
		mailBccADD = (ImageView) findViewById(R.id.mail_mailBcc_add_iv);
		recAddrADD.setOnClickListener(this);
		mailccADD.setOnClickListener(this);
		mailBccADD.setOnClickListener(this);

		recAddrET = (EditText) findViewById(R.id.mail_recAddr_et);
		mailCcET = (EditText) findViewById(R.id.mail_mailcc_et);
		mailBccET = (EditText) findViewById(R.id.mail_mailBcc_et);
		subjectET = (EditText) findViewById(R.id.mail_subjec_et);
		contentET = (EditText) findViewById(R.id.mail_content_et);

		String mailto = getIntent().getStringExtra("mailto") == null ? "" : getIntent().getStringExtra("mailto");
		recAddrET.setText(mailto);
	}

	@Override
	public void onClick(View v) {
		if (v == ivBack) {
			finish();
		} else if (v == ivSend) {
			String recAddrETStr = recAddrET.getText().toString().trim();
			if ("".equals(recAddrETStr)) {
				Toast.makeText(PublicMailActivity.this, "收件人不能为空", Toast.LENGTH_SHORT).show();
				return;
			} else if ("".equals(subjectET.getText().toString().trim())) {
				Toast.makeText(PublicMailActivity.this, "主题不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			// String[] recAddrArr = recAddrETStr.split(";");
			// boolean isTrue = true;
			// for(int i= 0; i< recAddrArr.length;i++){
			// isTrue = Utils.matchMail(recAddrArr[i]);
			// if(!isTrue){
			// break;
			// }
			// }
			// if(!isTrue){
			// Toast.makeText(PublicMailActivity.this, "收件人邮件地址不正确", 1).show();
			// return;
			// }

			new HttpManage(PublicMailActivity.this, PublicMailActivity.this, getsendMailParams(), 1);
			dialog = Utils.createProgressDialog(this, Utils.getLoadingMessage(PublicMailActivity.this, "发送邮件中..."));
			dialog.show();
		} else if (v == recAddrADD) {
			Intent qIntent = new Intent();
			qIntent.setAction("com.ibm.moa.contact.select");
			qIntent.addCategory("android.intent.category.DEFAULT");
			List<ResolveInfo> apps = getPackageManager().queryIntentActivities(qIntent, 0);
			if (apps != null && apps.size() > 0) {
				Intent intent = new Intent("com.ibm.moa.contact.select");
				intent.putExtra("userName", MailApplication.userCode);
				intent.putExtra("password", MailApplication.passWord);
				startActivityForResult(intent, 1);
			} else {
				Toast.makeText(PublicMailActivity.this, "请您在易办公中下载新版通讯录后再使用此功能！", Toast.LENGTH_SHORT).show();
			}
		} else if (v == mailccADD) {
			Intent qIntent = new Intent();
			qIntent.setAction("com.ibm.moa.contact.select");
			qIntent.addCategory("android.intent.category.DEFAULT");
			List<ResolveInfo> apps = getPackageManager().queryIntentActivities(qIntent, 0);
			if (apps != null && apps.size() > 0) {
				Intent intent = new Intent("com.ibm.moa.contact.select");
				intent.putExtra("userName", MailApplication.userCode);
				intent.putExtra("password", MailApplication.passWord);
				startActivityForResult(intent, 2);
			} else {
				Toast.makeText(PublicMailActivity.this, "请您在易办公中下载新版通讯录后再使用此功能！", Toast.LENGTH_SHORT).show();
			}

		} else if (v == mailBccADD) {
			Intent qIntent = new Intent();
			qIntent.setAction("com.ibm.moa.contact.select");
			qIntent.addCategory("android.intent.category.DEFAULT");
			List<ResolveInfo> apps = getPackageManager().queryIntentActivities(qIntent, 0);
			if (apps != null && apps.size() > 0) {
				Intent intent = new Intent("com.ibm.moa.contact.select");
				intent.putExtra("userName", MailApplication.userCode);
				intent.putExtra("password", MailApplication.passWord);
				startActivityForResult(intent, 3);
			} else {
				Toast.makeText(PublicMailActivity.this, "请您在易办公中下载新版通讯录后再使用此功能！", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private HashMap<String, String> getsendMailParams() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("invoke", "sendMail");
		map.put("userCode", MailApplication.userCode);
		map.put("password", MailApplication.passWord);
		String mailCcS = mailCcET.getText().toString().trim();
		String mailBccS = mailBccET.getText().toString().trim();
		String recAddrS = recAddrET.getText().toString().trim();
		mailCcS = mailCcS.replaceAll(";", ",");
		mailCcS = mailCcS.replaceAll("；", ",");
		mailBccS = mailBccS.replaceAll(";", ",");
		mailBccS = mailBccS.replaceAll("；", ",");
		recAddrS = recAddrS.replaceAll(";", ",");
		recAddrS = recAddrS.replaceAll("；", ",");

		StringBuilder xmlParam = new StringBuilder();
		xmlParam.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		xmlParam.append("<node>");
		xmlParam.append("<property name=\"mailBcc\">");
		xmlParam.append(mailBccS);
		xmlParam.append("</property>");
		xmlParam.append("<property name=\"mailCc\">");
		xmlParam.append(mailCcS);
		xmlParam.append("</property>");
		xmlParam.append("<property name=\"recAddr\">");
		xmlParam.append(recAddrS);
		xmlParam.append("</property>");
		xmlParam.append("<property name=\"plainContent\"><![CDATA[");
		xmlParam.append(contentET.getText().toString().trim());
		xmlParam.append("]]></property>");
		xmlParam.append("<property name=\"subject\">");
		xmlParam.append(subjectET.getText().toString().trim());
		xmlParam.append("</property>");
		if (mailInfo != null && mailInfo.attachments.size() > 0) {
			xmlParam.append("<list name=\"attachmentList\">");
			for (int i = 0; i < mailInfo.attachments.size(); i++) {
				xmlParam.append("<node>");
				xmlParam.append("<property name=\"attachName\">");
				xmlParam.append(mailInfo.attachments.get(i));
				xmlParam.append("</property>");
				// xmlParam.append("<property name=\"attachBase64\">");
				// xmlParam.append(mailInfo.attachments.get(i).);
				// xmlParam.append("</property>");
				xmlParam.append("</node>");
			}
			xmlParam.append("</list>");

		}
		xmlParam.append("</node>");

		map.put("mailInfoXML", xmlParam.toString());
		return map;
	}

	@Override
	public void action(int actionCode, String resultStr, int httpFlag) {
		switch (actionCode) {
		case HttpRequestListener.EVENT_GET_DATA_SUCCESS:
			switch (httpFlag) {
			case 1:
				try {
					Log.i("lgs", "" + resultStr);
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_SUCCESS, ParserRequest.ParsSendMail(resultStr));
					moreMeg.sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FAILURE, "返回信息错误");
					moreMeg.sendToTarget();
				}
				break;
			}
			break;
		case HttpRequestListener.EVENT_GET_DATA_FAIL:
			Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FAILURE, "网络请求失败");
			moreMeg.sendToTarget();
			break;
		}

	}

	@Override
	@SuppressWarnings("unchecked")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 1:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String recAddrStr = recAddrET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (email != null && !"".equals(email) && !recAddrStr.contains(email)) {
							if ("".equals(recAddrStr)) {
								recAddrStr += email;
							} else {
								recAddrStr += ";" + email;
							}
						}
					}
					recAddrET.setText(recAddrStr);
				}
				break;
			case 2:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String mailCCStr = mailCcET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (email != null && !"".equals(email) && !mailCCStr.contains(email)) {
							if ("".equals(mailCCStr)) {
								mailCCStr += email;
							} else {
								mailCCStr += ";" + email;
							}
						}
					}
					mailCcET.setText(mailCCStr);
				}
				break;
			case 3:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String mailBCCStr = mailBccET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (email != null && !"".equals(email) && !mailBCCStr.contains(email)) {
							if ("".equals(mailBCCStr)) {
								mailBCCStr += email;
							} else {
								mailBCCStr += ";" + email;
							}
						}
					}
					mailBccET.setText(mailBCCStr);
				}
				break;

			default:
				break;
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
